<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function maxSubsequence(nums, k) {
      const n = nums.length;
      const dp = new Array(n).fill(1);
      let res = 1;

      for (let i = 1; i < n; i++) {
        for (let j = 0; j < i; j++) {
          if (nums[i] - nums[j] <= k) {
            dp[i] = Math.max(dp[i], dp[j] + 1);
          }
        }
        res = Math.max(res, dp[i]);
      }
      return res;
    }
    console.log(maxSubsequence([7, 4, 5, 1, 8, 12, 4, 7], k = 5));
  </script>
</body>

</html>